<template>
  <div class="trading-panel-container">
    <!-- 自定义标题栏 -->
    <TitleBar
      :title="currentContract?.code || panelContract?.code"
      :show-maximize="false"
      :show-reduce="false"
    >
    </TitleBar>

    <!-- 主交易面板 -->
    <div class="trading-panel">
      <!-- 左侧操作列 -->
      <LeftControlPanel
        :current-contract="currentContract"
        :panel-contract="panelContract"
        :font-size="fontSize"
        :current-time="currentTime"
        :is-flashing="isFlashing"
        :price-change-percent="priceChangePercent"
        :total-volume="totalVolume"
        :total-position="totalPosition"
        :daily-position-change="dailyPositionChange"
        :red-value="Math.abs(shortPosition)"
        :blue-value="longPosition"
        :light-order-quantity="lightOrderQuantity"
        :heavy-order-quantity="heavyOrderQuantity"
        :order-type="orderType"
        :options="options"
        :net-position="netPosition"
        :c-position="cPosition"
        :t-position="tPosition"
        :pnl-value="calculatedPnlValue"
        :has-active-orders="activeOrders.length > 0"
        @zoom-in="zoomIn"
        @zoom-out="zoomOut"
        @cancel-all-orders="handleCancelAllOrders"
        @cancel-all-account-orders="handleCancelAllAccountOrders"
        @buy-long="handleBuyLong"
        @sell-short="handleSellShort"
        @cancel-order="handleCancelOrder"
        @cancel-all="handleCancelAll"
        @update:light-order-quantity="lightOrderQuantity = $event"
        @update:heavy-order-quantity="heavyOrderQuantity = $event"
        @update:order-type="orderType = $event"
        @update:options="options = $event"
        @panel-click="handleLeftPanelClick"
      />

      <!-- 右侧五列表格 -->
      <PriceTable
        ref="priceTableRef"
        :processed-order-book="processedOrderBook"
        :selected-cell="selectedCell"
        :font-size="fontSize"
        :cell-height="cellHeight"
        :light-order-quantity="lightOrderQuantity"
        :heavy-order-quantity="heavyOrderQuantity"
        :active-orders="activeOrders"
        :price-tick="currentPriceTick"
        :order-type="orderType"
        :options="options"
        :long-position="longPosition"
        :short-position="shortPosition"
        @order-click="handleOrderClick"
        @cancel-click="handleCancelClick"
        @place-order="handlePlaceOrder"
        @replace-order="handleReplaceOrder"
        @cancel-price-orders="handleCancelPriceOrders"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from "vue";
import TitleBar from "@/components/TitleBar.vue";

import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { useContractStore } from "@/stores/contractStore";
import type { ContractInfo } from "@/types/trading";
import { Modal } from "ant-design-vue";
import { invoke } from "@tauri-apps/api/core";
import { useRoute } from "vue-router";
import { debounce, throttle } from "@/utils/titleBarUtils";
import { emit, listen } from "@tauri-apps/api/event";

// 导入子组件
import LeftControlPanel from "../components/trading/LeftControlPanel.vue";
import PriceTable from "../components/trading/PriceTable.vue";

// 导入composables
import { useTrading } from "../composables/useTrading.js";
import { useMarketData } from "../composables/useMarketData.js";
import { usePositionData } from "../composables/usePositionData.js";
import { useSoundManager } from "../composables/useSoundManager";

// 使用路由
const route = useRoute();

// 获取当前窗口信息的函数
const getCurrentWindowInfo = async () => {
  try {
    const currentWindow = getCurrentWebviewWindow();
    if (currentWindow) {
      const position = await currentWindow.outerPosition();
      const isVisible = await currentWindow.isVisible();
      const isMinimized = await currentWindow.isMinimized();
      const isMaximized = await currentWindow.isMaximized();

      return {
        x: position.x,
        y: position.y,
        width: document.body.clientWidth,
        height: document.body.clientHeight,
        visible: isVisible,
        minimized: isMinimized,
        maximized: isMaximized,
      };
    }
  } catch (error) {
    console.error("获取窗口信息失败:", error);
  }

  // 返回默认值
  return {
    x: 0,
    y: 0,
    width: document.body.clientWidth || 800,
    height: document.body.clientHeight || 600,
    visible: true,
    minimized: false,
    maximized: false,
  };
};

// 使用声音管理器
const { playPlaceOrderSound, playCancelOrderSound, playSuccessSound } =
  useSoundManager();

// 组件引用
const priceTableRef = ref(null);

// 监听器取消函数
let orderUpdateUnlisten: (() => void) | null = null;
let tradeUnlisten: (() => void) | null = null;
let marketDataUnlisten: (() => void) | null = null;
let configRequestUnlisten: (() => void) | null = null;
let accountCancelUnlisten: (() => void) | null = null;

// 额外的监听器（用于精确通知）
let contractOrderUnlisten: (() => void) | null = null;
let globalOrderUnlisten: (() => void) | null = null;
let contractTradeUnlisten: (() => void) | null = null;
let globalTradeUnlisten: (() => void) | null = null;
let globalRestoreCenterUnlisten: (() => void) | null = null;

// 市价单订单引用集合（用于识别市价单，不显示k+数字）
const marketOrderRefs = new Set<string>();

// 订单类型存储（用于区分开仓单k+和平仓单p+）
const orderTypeMap = new Map<
  string,
  { isClosing: boolean; quantity: number }
>();

// 订单状态缓存，用于去重处理
const lastOrderStatus = new Map<
  string,
  { status: number; volume: number; volumeTraded: number; timestamp: number }
>();

// 注意：netPosition 来自 usePositionData composable，是 computed 属性

// 获取当前可挂单数量 - 支持吃多跑空/吃空跑多策略
const getAvailableQuantity = (
  orderType: "buy" | "sell",
  requestedQuantity: number
): { quantity: number; isClosing: boolean } => {
  const currentLongPosition = longPosition.value; // 多头持仓（正数）
  const currentShortPosition = Math.abs(shortPosition.value); // 空头持仓（绝对值）

  if (orderType === "buy") {
    // 买单逻辑
    if (currentLongPosition === 0 && currentShortPosition === 0) {
      // 情况1: 多空持仓都为空 - 开多单，显示k+数字
      return { quantity: requestedQuantity, isClosing: false };
    } else if (currentLongPosition === 0 && currentShortPosition > 0) {
      // 情况2: 有空头持仓，无多头持仓
      // 买单是跑多（平空仓），显示p+数字，数量限制为空单持仓数
      const maxClosing = currentShortPosition;
      const closingQuantity = Math.min(requestedQuantity, maxClosing);
      return { quantity: closingQuantity, isClosing: true };
    } else if (currentLongPosition > 0 && currentShortPosition === 0) {
      // 情况3: 有多头持仓，无空头持仓
      // 买单是加多仓（继续开多仓），显示k+数字
      return { quantity: requestedQuantity, isClosing: false };
    } else {
      // 情况4: 多空都有持仓 - 优先平空单
      const maxClosing = currentShortPosition;
      const closingQuantity = Math.min(requestedQuantity, maxClosing);
      return { quantity: closingQuantity, isClosing: true };
    }
  } else {
    // 卖单逻辑
    if (currentLongPosition === 0 && currentShortPosition === 0) {
      // 情况1: 多空持仓都为空 - 开空单，显示k+数字
      return { quantity: requestedQuantity, isClosing: false };
    } else if (currentLongPosition > 0 && currentShortPosition === 0) {
      // 情况2: 有多头持仓，无空头持仓
      // 卖单是跑空（平多仓），显示p+数字，数量限制为多单持仓数
      const maxClosing = currentLongPosition;
      const closingQuantity = Math.min(requestedQuantity, maxClosing);
      return { quantity: closingQuantity, isClosing: true };
    } else if (currentLongPosition === 0 && currentShortPosition > 0) {
      // 情况3: 有空头持仓，无多头持仓
      // 卖单是加空仓（继续开空仓），显示k+数字
      return { quantity: requestedQuantity, isClosing: false };
    } else {
      // 情况4: 多空都有持仓 - 优先平多单
      const maxClosing = currentLongPosition;
      const closingQuantity = Math.min(requestedQuantity, maxClosing);
      return { quantity: closingQuantity, isClosing: true };
    }
  }
};

// 手动清理空的挂单数据
const cleanupPendingOrders = () => {
  if (priceTableRef.value && priceTableRef.value.cleanupEmptyPendingOrders) {
    priceTableRef.value.cleanupEmptyPendingOrders();
  }
};

// 判断当前挂单是否为平仓单（根据持仓情况判断）
const isClosingOrderByPosition = (orderType: "buy" | "sell"): boolean => {
  const currentLongPosition = longPosition.value || 0;
  const currentShortPosition = Math.abs(shortPosition.value || 0);

  if (orderType === "buy") {
    // 买单：如果有空头持仓，则为平仓单
    return currentShortPosition > 0;
  } else {
    // 卖单：如果有多头持仓，则为平仓单
    return currentLongPosition > 0;
  }
};

// A模式限制检查：检查是否可以在新价位挂单（左侧按钮用，优化版：区分开仓单和平仓单）
const canPlaceOrderInAModeForLeftPanel = (
  orderDirection: "buy" | "sell",
  targetPrice: number
): { canPlace: boolean; existingPrices: number[]; message: string } => {
  if (orderType.value !== "A") {
    // B模式不限制
    return { canPlace: true, existingPrices: [], message: "" };
  }

  if (!priceTableRef.value || !priceTableRef.value.getPendingOrderPricesByType) {
    return { canPlace: true, existingPrices: [], message: "" };
  }

  // 判断当前挂单是否为平仓单
  const isClosing = isClosingOrderByPosition(orderDirection);

  // A模式：检查是否已有其他价位的【同类型】挂单
  // 关键优化：开仓单(k+)和平仓单(p+)分别检查，互不影响
  const allPendingPrices =
    priceTableRef.value.getPendingOrderPricesByType(orderDirection, isClosing);
  const existingPrices = allPendingPrices.filter(
    (price) => price !== targetPrice
  );

  if (existingPrices.length > 0) {
    const areaName = orderDirection === "buy" ? "多单区域" : "空单区域";
    const orderTypeName = isClosing ? "平仓单(p+)" : "开仓单(k+)";
    const message = `A模式限制：${areaName}已在价位 [${existingPrices.join(
      ", "
    )}] 有${orderTypeName}，同类型挂单只能在一个价位`;
    return { canPlace: false, existingPrices, message };
  }

  return { canPlace: true, existingPrices: [], message: "" };
};

// 获取合约代码和价格间距（在useTrading调用之前）
const getContractCodeFromUrl = (): string | null => {
  const urlParams = new URLSearchParams(
    window.location.hash.split("?")[1] || ""
  );
  return urlParams.get("contract");
};

const getPriceTickFromUrl = (): number | null => {
  const urlParams = new URLSearchParams(
    window.location.hash.split("?")[1] || ""
  );
  const priceTick = urlParams.get("priceTick");
  return priceTick ? parseFloat(priceTick) : null;
};

const initialContractCode =
  getContractCodeFromUrl() ||
  (Array.isArray(route.params.contract)
    ? route.params.contract[0]
    : route.params.contract);
const initialPriceTick = getPriceTickFromUrl();

// 创建响应式的当前合约代码，避免在每个函数中重复获取
const currentContractCode = computed(() => {
  const currentContractInfo = currentContract.value || panelContract.value;
  return currentContractInfo?.code || initialContractCode;
});

// 窗口ID管理 - 立即初始化
const windowId = ref<string>(
  (() => {
    try {
      const currentWindow = getCurrentWebviewWindow();
      const id = currentWindow.label;
      return id;
    } catch (error) {
      return "";
    }
  })()
);

// 使用composables - 传递合约代码实现数据隔离
const {
  selectedCell,
  lightOrderQuantity,
  heavyOrderQuantity,
  orderType,
  options,
  hasActiveOrder,
  lastOrderRef,
  activeOrders,
  cPosition,
  tPosition,
  handleOrderClick,
  placeOrder,
  cancelOrder,
  clearSelection,
  addActiveOrder,
  cancelAllOrders,
  cancelAllAccountOrders,
  incrementCancelCount,
  incrementTradeCount,
  removeActiveOrder,
} = useTrading(initialContractCode, windowId);

const {
  currentPrice,
  bid1Price,
  ask1Price,
  upperLimitPrice,
  lowerLimitPrice,
  priceChangePercent,
  totalVolume,
  totalPosition,
  dailyPositionChange,
  processedOrderBook,
  PRICE_LEVELS,
  currentSubscribedContract,
  panelInstanceId,
  calculateTableRows,
  generateEmptyPriceOrders,
  cleanupCurrentSubscription,
  updateMarketData,
  queryMarketData,
} = useMarketData(initialContractCode, initialPriceTick);

// 持仓数据管理 - 统一的持仓数据源
const {
  isLoading: isPositionLoading,
  longPosition,
  shortPosition,
  netPosition,
  queryPositionData,
  handleTradeNotification: handlePositionTradeNotification,
} = usePositionData();

// 计算PnL值：-redValue + blueValue
const calculatedPnlValue = computed(() => {
  const redValue = Math.abs(shortPosition.value);
  const blueValue = longPosition.value;
  return -redValue + blueValue;
});

// 合约状态管理
const { currentContract, setCurrentContract } = useContractStore();
const panelContract = ref<ContractInfo | null>(null);

// 价格间距管理
const currentPriceTick = ref<number>(1);

// 界面缩放
const fontSize = ref(11);
const cellHeight = ref(16);

// 使用全局时间服务
import { useGlobalTime } from "@/services/timeService";
import { contractService } from "@/services/contractService";
const { currentTime, isFlashing } = useGlobalTime({
  showMilliseconds: true,
  use24Hour: true,
  showDate: false,
});

// 缩放功能
const zoomIn = () => {
  fontSize.value = Math.min(fontSize.value + 1, 30);
  // 按比例缩放行高：基础行高18px对应字体16px，比例为1.125
  cellHeight.value = Math.round((fontSize.value + 4) * 1.125);
};

const zoomOut = () => {
  fontSize.value = Math.max(fontSize.value - 1, 2);
  // 按比例缩放行高：基础行高18px对应字体16px，比例为1.125
  cellHeight.value = Math.round((fontSize.value + 4) * 1.125);
};

// 时间更新现在由全局时间服务处理，无需本地定时器

// 窗口焦点状态
const isWindowFocused = ref(true);

// 键盘快捷键处理
const handleKeydown = (event: KeyboardEvent) => {
  // 空格键撤单
  if (event.code === "Space" || event.key === " ") {
    event.preventDefault();
    handleSpaceCancelOrder();
    return;
  }
  // 只有当前窗口获得焦点时才处理键盘事件
  if (!isWindowFocused.value) {
    return;
  }

  switch (event.key) {
    case "+":
    case "=":
      event.preventDefault();
      zoomIn();
      break;
    case "-":
      event.preventDefault();
      zoomOut();
      break;
    case "Escape":
      event.preventDefault();
      clearSelection();
      break;
    case "Enter":
      if (selectedCell.value) {
        event.preventDefault();
        placeOrder();
      }
      break;
    case "Delete":
    case "Backspace":
      if (selectedCell.value) {
        event.preventDefault();
        handleCancelOrder();
      }
      break;
  }
};

// 撤单点击处理
const handleCancelClick = async (
  section: "sell" | "buy",
  data: any,
  index: number,
  event?: MouseEvent
) => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }
  // 立即播放撤单提示音（不等待接口返回）
  playCancelOrderSound();

  // 设置选中状态
  selectedCell.value = {
    type: section,
    field: "cancel",
    value: data.price,
    data,
    index,
  };

  // 执行撤单操作
  try {
    await cancelOrder();
  } catch (error) {
    console.error("❌ 撤单点击失败:", error);
  }
};

// 处理空格键撤单
const handleSpaceCancelOrder = async () => {
  // 立即播放撤单提示音（不等待接口返回）
  playCancelOrderSound();

  // 空格键始终撤销账号下所有挂单，而不是单个合约的
  try {
    await cancelAllAccountOrders();
  } catch (error) {
    console.error("❌ 空格键撤单失败:", error);
  }
};

// 处理第一列点击撤单（撤销指定价位的所有挂单）
const handleCancelPriceOrders = async (price: number) => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }
  // 立即播放撤单提示音（不等待接口返回）
  playCancelOrderSound();

  try {
    // 获取活跃的trader session
    const activeSessionResult: any = await invoke("get_active_trader_session");
    if (!activeSessionResult.success) {
      return;
    }

    const traderSessionId = activeSessionResult.data;

    // 使用响应式的合约代码
    const contractCode = currentContractCode.value;

    if (!contractCode) {
      return;
    }

    // 获取该价位的所有买单和卖单引用
    const buyOrderRefs = priceTableRef.value?.getBuyOrderRefs(price) || [];
    const sellOrderRefs = priceTableRef.value?.getSellOrderRefs(price) || [];
    const allOrderRefs = [...buyOrderRefs, ...sellOrderRefs];

    if (allOrderRefs.length === 0) {
      return;
    }

    // 逐个撤销所有订单
    let successCount = 0;
    for (const orderRef of allOrderRefs) {
      const cancelResult: any = await invoke("cancel_order", {
        sessionId: traderSessionId,
        cancelRequest: {
          order_ref: orderRef,
          instrument_id: contractCode,
        },
      });

      if (cancelResult.success) {
        successCount++;

        // 增加撤单计数
        incrementCancelCount();

        // 从活跃订单列表中移除
        removeActiveOrder(orderRef);

        // 从价格表格中移除未成交订单显示
        // 判断是买单还是卖单
        if (buyOrderRefs.includes(orderRef)) {
          priceTableRef.value?.removePendingOrder("buy", price, orderRef, 1);
        } else if (sellOrderRefs.includes(orderRef)) {
          priceTableRef.value?.removePendingOrder("sell", price, orderRef, 1);
        }
      } else {
      }
    }
  } catch (error) {}
};

// 处理价格表格的下单请求
const handlePlaceOrder = async (
  orderType: "buy" | "sell",
  price: number,
  quantity: number,
  isHeavy: boolean,
  isMarketOrder: boolean = false
) => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 使用响应式的合约代码
  const contractCode = currentContractCode.value;

  if (!contractCode) {
    return;
  }

  // 检查可挂单数量和类型（仅对市价单进行限制）
  let actualQuantity = quantity;
  let isClosingOrder = false;

  if (isMarketOrder) {
    // 只有市价单才进行持仓检查和限制
    const availableInfo = getAvailableQuantity(orderType, quantity);
    actualQuantity = availableInfo.quantity;
    isClosingOrder = availableInfo.isClosing;
    // 只有在尝试平仓但没有持仓时才阻止下单
    if (actualQuantity === 0 && isClosingOrder) {
      return;
    }
  } else {
    // 普通挂单也需要进行持仓检查和限制（需求5：动态持仓跟踪）
    const availableInfo = getAvailableQuantity(orderType, quantity);
    actualQuantity = availableInfo.quantity;
    isClosingOrder = availableInfo.isClosing;
    // 如果是平仓单但没有可平仓的持仓，阻止下单
    if (actualQuantity === 0 && isClosingOrder) {
      return;
    }
  }
  try {
    // 获取活跃的trader session
    const activeSessionResult: any = await invoke("get_active_trader_session");

    let traderSessionId = "";
    if (activeSessionResult.success) {
      traderSessionId = activeSessionResult.data;
    } else {
      return;
    }

    // 构造订单请求
    const orderRequest = {
      instrument_id: contractCode,
      direction: orderType === "buy" ? "0" : "1", // 买入或卖出
      price: price,
      volume: actualQuantity, // 使用调整后的数量
      order_type: "2", // 限价单
      offset_flag: isClosingOrder ? "1" : "0", // 平仓单使用'1'，开仓单使用'0'
      hedge_flag: "1", // 投机
      time_condition: "3", // 当日有效
      volume_condition: "1", // 任何数量
    };

    // 创建窗口上下文
    const windowContext = {
      windowId: windowId.value,
      contractCode: contractCode,
    };

    // 调用挂单接口
    const result: any = await invoke("insert_order", {
      sessionId: traderSessionId,
      order: orderRequest,
      windowContext: windowContext,
    });

    if (result.success) {
      // 从返回消息中提取订单引用
      const orderRefMatch = result.data.match(/订单引用:\s*(\d+)/);
      let orderRef = null;

      if (orderRefMatch) {
        orderRef = orderRefMatch[1];
      } else {
        // 如果无法提取订单引用，使用时间戳作为临时引用
        orderRef = Date.now().toString();
      }

      // 如果是市价单，记录订单引用（用于不显示k+数字）
      if (isMarketOrder && orderRef) {
        marketOrderRefs.add(orderRef);
      }

      // 记录订单的开仓/平仓信息（用于显示k+或p+）
      const orderKey = orderRef; // 简化key格式，只使用orderRef
      orderTypeMap.set(orderKey, {
        isClosing: isClosingOrder,
        quantity: actualQuantity,
      });
      addActiveOrder(
        orderRef,
        orderType === "buy" ? "买入" : "卖出",
        price,
        contractCode
      );

      // 增加操作计数（挂单）
      incrementCancelCount(contractCode);

      // 播放下单成功声音
      playPlaceOrderSound();
    }
  } catch (error) {}
};

// 处理替换订单请求（撤销+重新挂单）
const handleReplaceOrder = async (
  orderType: "buy" | "sell",
  price: number,
  quantity: number,
  isHeavy: boolean,
  existingRefs: string[]
) => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }
  try {
    // 获取活跃的trader session
    const activeSessionResult: any = await invoke("get_active_trader_session");
    if (!activeSessionResult.success) {
      return;
    }

    const traderSessionId = activeSessionResult.data;

    // 使用响应式的合约代码
    const contractCode = currentContractCode.value;

    if (!contractCode) {
      return;
    }

    for (const orderRef of existingRefs) {
      const cancelResult: any = await invoke("cancel_order", {
        sessionId: traderSessionId,
        cancelRequest: {
          order_ref: orderRef,
          instrument_id: contractCode,
        },
      });

      if (cancelResult.success) {
        // 增加撤单计数（同价位再次挂单或单点位模式换价挂单）
        incrementCancelCount(contractCode);
        
        // 从价格表格中移除未成交订单
        priceTableRef.value?.removePendingOrder(orderType, price, orderRef, 1);
      }
    }

    // 等待一小段时间确保撤销完成
    await new Promise((resolve) => setTimeout(resolve, 100));

    // 步骤2: 挂新订单
    await handlePlaceOrder(orderType, price, quantity, isHeavy);
  } catch (error) {
    console.error("💥 替换订单失败:", error);
  }
};

// 创建防抖版本的下单函数
const debouncedBuyLong = debounce(async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 使用响应式的合约代码
  const contractCode = currentContractCode.value;

  if (!contractCode) {
    return;
  }

  try {
    // 检查必要的参数
    if (!currentPrice.value || currentPrice.value <= 0) {
      return;
    }

    if (!lightOrderQuantity.value || lightOrderQuantity.value <= 0) {
      return;
    }

    // 使用买一价-1作为挂单价格（排队等待，不会立即成交）
    const orderPrice =
      bid1Price.value > 0 ? bid1Price.value - 1 : currentPrice.value - 10;
    const quantity = lightOrderQuantity.value;
    await handlePlaceOrder("buy", orderPrice, quantity, false);
  } catch (error) {}
}, 500); // 0.5秒防抖

const debouncedSellShort = debounce(async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 使用响应式的合约代码
  const contractCode = currentContractCode.value;

  if (!contractCode) {
    return;
  }

  try {
    // 检查必要的参数
    if (!currentPrice.value || currentPrice.value <= 0) {
      return;
    }

    if (!lightOrderQuantity.value || lightOrderQuantity.value <= 0) {
      return;
    }
    // 使用卖一价+1作为挂单价格（排队等待，不会立即成交）
    let orderPrice =
      ask1Price.value > 0 ? ask1Price.value + 1 : currentPrice.value + 10;

    // 检查价格是否在涨跌停板范围内
    if (upperLimitPrice.value > 0 && orderPrice > upperLimitPrice.value) {
      orderPrice = upperLimitPrice.value;
    }

    const quantity = lightOrderQuantity.value;

    await handlePlaceOrder("sell", orderPrice, quantity, false);
  } catch (error) {}
}, 500); // 0.5秒防抖

// 左侧按钮事件处理函数
const handleBuyLong = async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 使用响应式的合约代码
  const contractCode = currentContractCode.value;

  if (!contractCode) {
    return;
  }

  // 检查是否开启防连点
  if (options.value.noCombo) {
    debouncedBuyLong();
    return;
  }

  try {
    // 检查必要的参数
    if (!currentPrice.value || currentPrice.value <= 0) {
      return;
    }

    if (!lightOrderQuantity.value || lightOrderQuantity.value <= 0) {
      return;
    }

    // 使用买一价-1作为挂单价格（排队等待，不会立即成交）
    const orderPrice =
      bid1Price.value > 0 ? bid1Price.value - 1 : currentPrice.value - 10;
    const quantity = lightOrderQuantity.value;
    // 根据模式决定下单策略
    if (orderType.value === "B") {
      await handlePlaceOrder("buy", orderPrice, quantity, false);
    } else {
      const aModeCheck = canPlaceOrderInAModeForLeftPanel(
        "buy",
        Math.round(orderPrice)
      );
      if (!aModeCheck.canPlace) {
        return;
      }

      // A模式：检查该价位是否有未成交订单，如果有则先撤销再重新挂单
      const existingRefs =
        priceTableRef.value?.getBuyOrderRefs(Math.round(orderPrice)) || [];
      if (existingRefs.length > 0) {
        await handleReplaceOrder(
          "buy",
          orderPrice,
          quantity,
          false,
          existingRefs
        );
      } else {
        await handlePlaceOrder("buy", orderPrice, quantity, false);
      }
    }
  } catch (error) {}
};

const handleSellShort = async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 使用响应式的合约代码
  const contractCode = currentContractCode.value;

  if (!contractCode) {
    return;
  }

  // 检查是否开启防连点
  if (options.value.noCombo) {
    debouncedSellShort();
    return;
  }

  try {
    // 检查必要的参数
    if (!currentPrice.value || currentPrice.value <= 0) {
      return;
    }

    if (!lightOrderQuantity.value || lightOrderQuantity.value <= 0) {
      return;
    }

    // 使用卖一价+1作为挂单价格（排队等待，不会立即成交）
    let orderPrice =
      ask1Price.value > 0 ? ask1Price.value + 1 : currentPrice.value + 10;

    // 检查价格是否在涨跌停板范围内
    if (upperLimitPrice.value > 0 && orderPrice > upperLimitPrice.value) {
      orderPrice = upperLimitPrice.value;
    }
    if (lowerLimitPrice.value > 0 && orderPrice < lowerLimitPrice.value) {
      orderPrice = lowerLimitPrice.value;
    }
    const quantity = lightOrderQuantity.value;

    // 根据模式决定下单策略
    if (orderType.value === "B") {
      await handlePlaceOrder("sell", orderPrice, quantity, false);
    } else {
      const aModeCheck = canPlaceOrderInAModeForLeftPanel(
        "sell",
        Math.round(orderPrice)
      );
      if (!aModeCheck.canPlace) {
        return;
      }

      const existingRefs =
        priceTableRef.value?.getSellOrderRefs(Math.round(orderPrice)) || [];
      if (existingRefs.length > 0) {
        await handleReplaceOrder(
          "sell",
          orderPrice,
          quantity,
          false,
          existingRefs
        );
      } else {
        await handlePlaceOrder("sell", orderPrice, quantity, false);
      }
    }
  } catch (error) {}
};

const handleCancelOrder = async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }
  // 立即播放撤单提示音（不等待接口返回）
  playCancelOrderSound();

  try {
    await cancelOrder();
  } catch (error) {
    console.error("💥 撤销订单失败");
  }
};

const handleCancelAll = async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 立即播放撤单提示音（不等待接口返回）
  playCancelOrderSound();

  try {
    await cancelAllOrders();
  } catch (error) {
    console.error("💥 全撤订单失败");
  }
};

// 全撤处理
const handleCancelAllOrders = async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 立即播放撤单提示音（不等待接口返回）
  playCancelOrderSound();

  await cancelAllOrders();
};

// 账号全撤处理
const handleCancelAllAccountOrders = async () => {
  // 检查窗口焦点状态
  if (!isWindowFocused.value) {
    return;
  }

  // 显示确认对话框
  Modal.confirm({
    title: "确认撤销账号下所有挂单",
    content:
      "⚠️ 这将撤销您账号下所有未成交的订单，包括其他页面的挂单。\n\n确定要继续吗？",
    okText: "确定撤销",
    cancelText: "取消",
    okType: "danger",
    width: 500,
    onOk: async () => {
      // 立即播放撤单提示音（不等待接口返回）
      playCancelOrderSound();
      const result = await cancelAllAccountOrders();
      if (result.success) {
        if (result.details) {
          Modal.info({
            title: "账号全撤结果",
            content: `${
              result.message
            }\n\n详细结果:\n${result.details.results.join("\n")}`,
            width: 700,
            okText: "确定",
          });
        }
      } else {
      }
    },
  });
};

// 窗口大小变化监听器
const handleResize = () => {
  setTimeout(() => {
    if (priceTableRef.value?.tableContainer) {
      calculateTableRows(priceTableRef.value.tableContainer);
      generateEmptyPriceOrders();
    }
  }, 100);
};

// 初始化合约行情订阅
const initializeContractSubscription = async () => {
  // 从URL参数获取合约代码
  const contractCodeFromUrl = getContractCodeFromUrl();

  if (contractCodeFromUrl) {
    // 直接创建合约信息，不需要查询全量合约数据
    const contractInfo =
      contractService.getContractInfoByCode(contractCodeFromUrl);
    setCurrentContract(contractInfo);
    panelContract.value = contractInfo;

    // 保存面板合约信息
    savePanelContractInfo();

    // 直接订阅指定合约的行情数据，不需要获取全量合约数据
    await queryMarketData(contractCodeFromUrl);
  } else {
    // 如果没有URL参数，尝试使用当前合约存储中的合约
    const currentContractInfo = currentContract.value;
    
    if (currentContractInfo) {
      setCurrentContract(currentContractInfo);
      panelContract.value = currentContractInfo;
      
      // 保存面板合约信息
      savePanelContractInfo();
      
      // 订阅当前合约的行情数据
      await queryMarketData(currentContractInfo.code);
    } else {
      console.warn('⚠️ 未指定合约代码，请通过合约搜索选择合约');
    }
  }
};

// 处理订单状态更新 - 完整版本，满足所有需求
const handleOrderStatusUpdate = (orderData: any) => {
  // 去重处理：检查是否为重复事件
  const orderKey = `${orderData.order_ref}_${orderData.session_id}`;
  const currentStatus = {
    status: orderData.status,
    volume: orderData.volume,
    volumeTraded: orderData.volume_traded || 0,
    timestamp: Date.now(),
  };

  const lastStatus = lastOrderStatus.get(orderKey);
  if (
    lastStatus &&
    lastStatus.status === currentStatus.status &&
    lastStatus.volume === currentStatus.volume &&
    lastStatus.volumeTraded === currentStatus.volumeTraded &&
    currentStatus.timestamp - lastStatus.timestamp < 1000
  ) {
    return;
  }

  // 更新状态缓存
  lastOrderStatus.set(orderKey, currentStatus);

  // 提取订单信息
  const orderRef = orderData.order_ref || orderData.ref;
  const status = orderData.status;
  const price = orderData.price;
  const volume = orderData.volume;
  const volumeTraded = orderData.volume_traded || 0;
  const direction = orderData.direction;

  // 数据完整性检查（修复：允许volume为0）
  if (
    !orderRef ||
    status === undefined ||
    !price ||
    volume === undefined ||
    direction === undefined
  ) {
    return;
  }

  // 修复：处理VolumeTotal异常的情况
  let actualVolume = volume;
  let actualVolumeTraded = volumeTraded;

  // 如果VolumeTotal为0但VolumeTraded>0，说明数据异常，需要修正
  if (volume === 0 && volumeTraded > 0) {
    // 从本地记录中查找原始挂单数量
    const currentOrderRefs =
      direction === "0"
        ? priceTableRef.value?.getBuyOrderRefs(Math.round(price)) || []
        : priceTableRef.value?.getSellOrderRefs(Math.round(price)) || [];

    if (currentOrderRefs.includes(orderRef.toString()) && priceTableRef.value) {
      // 如果订单存在，说明之前记录过，使用已成交数量作为原始数量
      actualVolume = volumeTraded;
    }
  }

  const remainingVolume = actualVolume - actualVolumeTraded;
  const orderType = direction === "0" ? "buy" : "sell";
  const roundedPrice = Math.round(price);
  // 状态码说明：
  // 48 = 全部成交
  // 49 = 部分成交还在队列中
  // 51 = 未成交还在队列中
  // 53 = 撤单
  // 97 = 未知状态（刚提交）

  if (!priceTableRef.value) {
    return;
  }

  if (status === 48 || status === 53) {
    // 需求3: 全部成交或撤单后，第一列k会消失
    const statusText = status === 48 ? "全部成交" : "已撤单";
    // 强制移除订单，无论剩余数量计算结果如何
    if (priceTableRef.value) {
      // 获取移除前的数量
      const beforeCount =
        orderType === "buy"
          ? priceTableRef.value.getBuyOrderCount(roundedPrice)
          : priceTableRef.value.getSellOrderCount(roundedPrice);

      priceTableRef.value.removePendingOrder(
        orderType,
        roundedPrice,
        orderRef.toString(),
        actualVolume
      );

      // 获取移除后的数量
      const afterCount =
        orderType === "buy"
          ? priceTableRef.value.getBuyOrderCount(roundedPrice)
          : priceTableRef.value.getSellOrderCount(roundedPrice);

      // 检查是否为普通挂单的全部成交（用于第三列颜色变浅效果）
      // 只有状态48（全部成交）才触发变浅效果，取消挂单不触发
      const isMarketOrder = marketOrderRefs.has(orderRef.toString());
      const isFullyFilled = orderData.status === 48; // 48 = 全部成交
      if (
        !isMarketOrder &&
        afterCount === 0 &&
        beforeCount > 0 &&
        isFullyFilled
      ) {
        // 普通挂单全部成交，设置最近成交价位（第三列颜色变浅）
        priceTableRef.value.setRecentlyFilledInfo(roundedPrice, orderType);

        // 记录成交订单的第一列填充信息
        // 根据订单类型确定区域：买单在多单区域(buy)，卖单在空单区域(sell)
        const section = orderType === "buy" ? "buy" : "sell";
        priceTableRef.value.recordFilledOrderFill(roundedPrice, section);
      }

      // 市价单成交后不再立即清除第五列填充显示，保持填充直到下一次市价成交
      if (isMarketOrder) {
        // 清除订单引用记录，但保持第五列填充显示
        marketOrderRefs.delete(orderRef.toString());
      }
    }
  } else if (status === 49) {
    // 需求2: 部分成交后动态展示k+未成交数
    if (remainingVolume > 0) {
      // 直接设置该订单的剩余数量（新的数据结构支持覆盖）
      // 检查是否为平仓单
      const orderKey = orderRef; // 简化key格式，只使用orderRef
      const orderInfo = orderTypeMap.get(orderKey);
      const isClosing = orderInfo?.isClosing || false;

      priceTableRef.value.addPendingOrder(
        orderType,
        roundedPrice,
        orderRef.toString(),
        remainingVolume,
        isClosing
      );
    } else {
      // 如果没有剩余，移除订单
      priceTableRef.value.removePendingOrder(
        orderType,
        roundedPrice,
        orderRef.toString(),
        0
      );
    }
  } else if (status === 51 || status === 97) {
    // 需求1: 挂空单、多单时，第一列都会展示k+挂单数
    const statusText =
      status === 51 ? "未成交还在队列中" : "未知状态（刚提交）";

    // 检查是否为市价单（市价单不显示k+数字）
    if (marketOrderRefs.has(orderRef.toString())) {
      return;
    }

    // 添加或更新订单的未成交数量
    if (priceTableRef.value) {
      // 检查是否为平仓单
      const orderKey = orderRef; // 简化key格式，只使用orderRef
      const orderInfo = orderTypeMap.get(orderKey);
      const isClosing = orderInfo?.isClosing || false;

      priceTableRef.value.addPendingOrder(
        orderType,
        roundedPrice,
        orderRef.toString(),
        remainingVolume,
        isClosing
      );
    }
  }
};

// 处理成交通知 - 增量更新版本
const handleTradeNotification = async (tradeData: any) => {
  const orderRef = tradeData.order_ref || tradeData.ref;

  // 播放成交成功声音
  playSuccessSound();

  // 1. 判断是开仓还是平仓，以进行正确的增量计算
  try {
    const activeSessionResult: any = await invoke("get_active_trader_session");
    if (!activeSessionResult.success) {
      return;
    }
    const traderSessionId = activeSessionResult.data;
    const orderKey = orderRef; // 简化key格式，只使用orderRef

    const orderInfo = orderTypeMap.get(orderKey);
    // 如果在映射中找不到订单（例如，非本窗口下的订单），默认为开仓，但这可能不完全准确
    const isClosing = orderInfo ? orderInfo.isClosing : false;

    // 2. 调用 usePositionData 中的增量更新方法
    handlePositionTradeNotification(tradeData, isClosing);

    // 3. 增加成交计数 - 修复tPosition不刷新的问题
    const tradeContractCode = tradeData.instrument_id;
    if (
      tradeContractCode === currentContract.value?.code ||
      tradeContractCode === initialContractCode
    ) {
      incrementTradeCount(tradeContractCode, tradeData.volume);
    }

    // 4. 成交通知处理完成后，清除订单类型记录
    orderTypeMap.delete(orderKey);
  } catch (error) {
    console.error("❌ [Frontend] 增量更新持仓失败:", error);
  }
};

// 处理左侧面板点击事件 - 实现全局恢复居中功能
const handleLeftPanelClick = async (event: MouseEvent) => {
  // 发送全局事件，通知所有交易面板（包括当前窗口）恢复居中
  try {
    await emit('global-restore-center-view', {
      sourceWindowId: windowId.value,
      timestamp: Date.now()
    });
    console.log('🎯 发送全局恢复居中事件，所有窗口将恢复');
  } catch (error) {
    console.error('❌ 发送全局恢复居中事件失败:', error);
  }
};

// 页面加载时获取当前未成交订单和持仓
const loadInitialData = async () => {
  // 1. 恢复未成交订单
  await loadCurrentPendingOrders();

  // 2. 查询持仓数据
  await queryPositionData(panelContract.value?.code);
};

// 页面加载时获取当前未成交订单 - 需求2: 页面刷新时动态展示k+未成交数
const loadCurrentPendingOrders = async () => {
  try {
    // 获取活跃的trader session
    const activeSessionResult: any = await invoke("get_active_trader_session");
    if (!activeSessionResult.success) {
      return;
    }

    const traderSessionId = activeSessionResult.data;

    // 调用后端接口查询所有未成交订单
    const result: any = await invoke("query_all_orders", {
      sessionId: traderSessionId,
    });

    if (result.success && result.data) {
      // 清空现有的未成交订单显示
      if (priceTableRef.value) {
        priceTableRef.value.clearAllPendingOrders();
      }

      // 重新添加真正未成交的订单
      let addedCount = 0;
      let totalRemainingVolume = 0;

      for (const order of result.data) {
        try {
          // 只处理有未成交数量的订单
          const remainingVolume = order.volume - order.volume_traded;

          if (
            order.order_status === "未成交还在队列中" &&
            remainingVolume > 0
          ) {
            const price = Math.round(order.price);
            const orderType = order.direction === "买入" ? "buy" : "sell";
            const orderRef = order.order_ref;

            if (priceTableRef.value) {
              // 检查是否为平仓单
              const orderKey = orderRef; // 简化key格式，只使用orderRef
              const orderInfo = orderTypeMap.get(orderKey);
              const isClosing = orderInfo?.isClosing || false;

              priceTableRef.value.addPendingOrder(
                orderType,
                price,
                orderRef,
                remainingVolume,
                isClosing
              );
              addedCount++;
              totalRemainingVolume += remainingVolume;
            }
          }
        } catch (error) {
          console.error("❌ [Frontend] 处理订单失败:", order, error);
        }
      }
    }
  } catch (error) {
    console.error("❌ [Frontend] 页面刷新时恢复k+数字状态失败:", error);
  }
};

// 市场数据更新时同步订单状态 - 实现精确的k+数字显示
const syncOrderStatusOnMarketUpdate = async () => {
  // 防止频繁调用，使用节流 - 最多每5秒执行一次
  const now = Date.now();
  if (
    syncOrderStatusOnMarketUpdate.isRunning ||
    (syncOrderStatusOnMarketUpdate.lastRun &&
      now - syncOrderStatusOnMarketUpdate.lastRun < 5000)
  ) {
    return;
  }

  syncOrderStatusOnMarketUpdate.isRunning = true;
  syncOrderStatusOnMarketUpdate.lastRun = now;

  try {
    // 获取活跃的trader session
    const activeSessionResult: any = await invoke("get_active_trader_session");
    if (!activeSessionResult.success) {
      return;
    }

    const traderSessionId = activeSessionResult.data;

    // 查询当前所有订单状态
    const result: any = await invoke("query_all_orders", {
      sessionId: traderSessionId,
    });

    if (result.success && result.data) {
      let updatedCount = 0;

      for (const order of result.data) {
        try {
          // 计算剩余未成交数量：k+未成交 = k+(挂单数-已成交数)
          const remainingVolume = order.volume - order.volume_traded;
          const price = Math.round(order.price);
          const orderType = order.direction === "买入" ? "buy" : "sell";
          const orderRef = order.order_ref;

          if (
            order.order_status === "未成交还在队列中" &&
            remainingVolume > 0
          ) {
            // 更新k+数字为实际剩余数量
            if (priceTableRef.value) {
              // 获取当前订单引用列表
              const currentOrderRefs =
                orderType === "buy"
                  ? priceTableRef.value.getBuyOrderRefs(price)
                  : priceTableRef.value.getSellOrderRefs(price);

              if (currentOrderRefs.includes(orderRef)) {
                // 订单存在，更新数量为实际剩余数量
                // 检查是否为平仓单
                const orderKey = orderRef; // 简化key格式，只使用orderRef
                const orderInfo = orderTypeMap.get(orderKey);
                const isClosing = orderInfo?.isClosing || false;

                priceTableRef.value.addPendingOrder(
                  orderType,
                  price,
                  orderRef,
                  remainingVolume,
                  isClosing
                );
                updatedCount++;
              }
            }
          } else if (remainingVolume <= 0 && priceTableRef.value) {
            // 当挂单数已全部成交后，k+数字在下次刷新时消失掉
            const currentOrderRefs =
              orderType === "buy"
                ? priceTableRef.value.getBuyOrderRefs(price)
                : priceTableRef.value.getSellOrderRefs(price);

            if (currentOrderRefs.includes(orderRef)) {
              priceTableRef.value.removePendingOrder(
                orderType,
                price,
                orderRef,
                0
              );
              updatedCount++;
            }
          }
        } catch (error) {
          console.error("❌ [Frontend] 同步订单状态失败:", order, error);
        }
      }
    }
  } catch (error) {
    console.error("❌ [Frontend] 市场数据同步订单状态失败:", error);
  } finally {
    syncOrderStatusOnMarketUpdate.isRunning = false;
  }
};

// 添加节流标记
syncOrderStatusOnMarketUpdate.isRunning = false;
syncOrderStatusOnMarketUpdate.lastRun = 0;

// 保存面板合约信息到localStorage的函数
const savePanelContractInfo = () => {
  if (windowId.value && panelContract.value) {
    try {
      // 获取现有的面板合约映射
      const existingData = localStorage.getItem("panel_contracts");
      const panelContracts = existingData ? JSON.parse(existingData) : {};

      // 更新当前面板的合约信息
      panelContracts[windowId.value] = {
        code: panelContract.value.code,
        name: panelContract.value.name,
        timestamp: new Date().toISOString(),
      };

      // 保存到localStorage
      localStorage.setItem("panel_contracts", JSON.stringify(panelContracts));
    } catch (error) {
      console.error("保存面板合约信息失败:", error);
    }
  }
};

// 窗口焦点事件处理
const handleWindowFocus = () => {
  isWindowFocused.value = true;
};

const handleWindowBlur = () => {
  isWindowFocused.value = false;
};

// 组件挂载
onMounted(async () => {
  // windowId 现在在声明时已初始化，无需再次调用 initializeWindowId()
  // 时间更新由全局时间服务处理

  // 初始化价格间距（从useMarketData中获取）
  currentPriceTick.value = PRICE_LEVELS.value.PRICE_STEP;

  // 添加窗口焦点监听器
  window.addEventListener("focus", handleWindowFocus);
  window.addEventListener("blur", handleWindowBlur);

  document.addEventListener("keydown", handleKeydown);
  window.addEventListener("resize", handleResize);

  await nextTick();
  setTimeout(() => {
    if (priceTableRef.value?.tableContainer) {
      calculateTableRows(priceTableRef.value.tableContainer);
      generateEmptyPriceOrders();
    }
  }, 200);

  // 初始化合约行情订阅
  setTimeout(() => {
    initializeContractSubscription();
  }, 500);

  // 加载初始数据（订单和持仓）
  setTimeout(() => {
    loadInitialData();
  }, 1000); // 延迟以确保CTP会话准备就绪

  try {
    const { listen } = await import("@tauri-apps/api/event");
    // 监听订单状态更新 - 优先监听特定窗口的事件
    const windowSpecificOrderEvent = `order_update_${windowId.value}`;
    const contractSpecificOrderEvent = `order_update_${initialContractCode}`;
    orderUpdateUnlisten = await listen(windowSpecificOrderEvent, (event) => {
      handleOrderStatusUpdate(event.payload);
    });
    contractOrderUnlisten = await listen(
      contractSpecificOrderEvent,
      (event) => {
        handleOrderStatusUpdate(event.payload);
      }
    );

    // 保留全局事件监听作为后备（向后兼容）
    globalOrderUnlisten = await listen("order_update", (event) => {
      handleOrderStatusUpdate(event.payload);
    });

    // 监听成交通知 - 优先监听特定窗口的事件
    const windowSpecificTradeEvent = `trade_notification_${windowId.value}`;
    const contractSpecificTradeEvent = `trade_notification_${initialContractCode}`;
    tradeUnlisten = await listen(windowSpecificTradeEvent, (event: any) => {
      handleTradeNotification(event.payload);
    });
    contractTradeUnlisten = await listen(
      contractSpecificTradeEvent,
      (event: any) => {
        handleTradeNotification(event.payload);
      }
    );

    // 保留全局事件监听作为后备（向后兼容）
    globalTradeUnlisten = await listen("trade_notification", (event: any) => {
      handleTradeNotification(event.payload);
    });

    // 监听全局恢复居中事件
    globalRestoreCenterUnlisten = await listen("global-restore-center-view", (event: any) => {
      try {
        // 所有窗口都执行恢复居中操作
        if (priceTableRef.value?.restoreCenterView) {
          priceTableRef.value.restoreCenterView();
          console.log('🎯 收到全局恢复居中事件，已恢复居中显示');
        }
      } catch (error) {
        console.error('❌ 处理全局恢复居中事件失败:', error);
      }
    });
    marketDataUnlisten = await listen("market_data", (event: any) => {
      try {
        const data = event.payload;

        // 验证数据是否属于当前面板的合约
        if (
          !data.instrument_id ||
          data.instrument_id !== currentSubscribedContract.value
        ) {
          // 不记录日志，避免过多输出
          return;
        }

        updateMarketData(data);
      } catch (error) {}
    });

    // 监听面板配置请求 - 使用窗口ID而不是面板实例ID
    configRequestUnlisten = await listen(
      `get-panel-config-${windowId.value}`,
      async (event) => {
        try {
          const windowInfo = await getCurrentWindowInfo();
          const panelConfig = {
            window: windowInfo,
            tradingState: {
              currentPrice: currentPrice.value || 0,
              fontSize: fontSize.value,
              cellHeight: cellHeight.value,
              orderType: orderType.value,
              lightOrderQuantity: lightOrderQuantity.value,
              heavyOrderQuantity: heavyOrderQuantity.value,
              positionMode: "open", // 可以根据实际状态设置
              cancelMode: "limited", // 可以根据实际状态设置
              maxCancelOrders: 489, // 可以根据实际状态设置
              currentCancelCount: 0, // 可以根据实际状态设置
            },
            marketData: {
              totalVolume: totalVolume.value || 0,
              totalPosition: totalPosition.value || 0,
              dailyPositionChange: dailyPositionChange.value || 0,
              priceChangePercent: priceChangePercent.value || 0,
            },
            priceTick: currentPriceTick.value,
          };

          const { emit } = await import("@tauri-apps/api/event");
          await emit(`panel-config-response-${windowId.value}`, panelConfig);
        } catch (error) {}
      }
    );

    // 监听账号全撤单事件 - 使用窗口特定的事件名
    const { getCurrentWindow } = await import("@tauri-apps/api/window");
    const currentWindow = getCurrentWindow();
    const windowLabel = currentWindow.label;
    const windowSpecificCancelEvent = `account-cancel-orders-${windowLabel}`;
    // 先清理旧的监听器（如果存在）
    if (accountCancelUnlisten) {
      accountCancelUnlisten();
      accountCancelUnlisten = null;
    }

    accountCancelUnlisten = await listen(
      windowSpecificCancelEvent,
      (event: any) => {
        try {
          const { contractCancelCounts } = event.payload;
          const panelContractCode =
            currentContract.value?.code || initialContractCode;
          // 检查当前合约是否有撤单
          if (contractCancelCounts && contractCancelCounts[panelContractCode]) {
            const cancelCount = contractCancelCounts[panelContractCode];

            // 调用撤单计数增加函数 - 不传递合约代码，让它自动匹配
            incrementCancelCount(null, cancelCount);
          }
        } catch (error) {}
      }
    );
  } catch (error) {
    console.error("❌ [Frontend] 事件监听器注册失败:", error);
  }

  // 页面加载时初始化数据（延迟执行，确保CTP连接完成）
  setTimeout(async () => {
    try {
      // 1. 先恢复未成交订单
      await loadCurrentPendingOrders();

      // 2. 清理空的挂单数据
      cleanupPendingOrders();

      // 3. 再查询持仓数据（只查询一次）
      await queryPositionData();
    } catch (error) {}
  }, 2500);
});

// 监听合约变化
watch(
  () => currentContract.value,
  async (newContract, oldContract) => {
    if (newContract && newContract.code !== oldContract?.code) {
      // 更新面板合约信息
      panelContract.value = newContract;

      // 保存面板合约信息
      savePanelContractInfo();

      // 重新订阅新合约的行情数据（直接订阅，不查询全量合约数据）
      await queryMarketData(newContract.code);
    }
  },
  { immediate: false } // 不立即执行，避免初始化时重复订阅
);

// 清理面板合约信息的函数
const cleanupPanelContractInfo = () => {
  if (windowId.value) {
    try {
      const existingData = localStorage.getItem("panel_contracts");
      if (existingData) {
        const panelContracts = JSON.parse(existingData);
        delete panelContracts[windowId.value];
        localStorage.setItem("panel_contracts", JSON.stringify(panelContracts));
      }
    } catch (error) {}
  }
};

// 组件卸载
onUnmounted(() => {
  // 时间更新由全局时间服务处理，无需手动停止
  document.removeEventListener("keydown", handleKeydown);
  window.removeEventListener("resize", handleResize);

  // 清理窗口焦点监听器
  window.removeEventListener("focus", handleWindowFocus);
  window.removeEventListener("blur", handleWindowBlur);

  // 清理面板合约信息
  cleanupPanelContractInfo();

  // 清理CTP事件监听器（同步清理，避免异步操作）
  if (orderUpdateUnlisten) {
    orderUpdateUnlisten();
  }

  if (contractOrderUnlisten) {
    contractOrderUnlisten();
  }

  if (globalOrderUnlisten) {
    globalOrderUnlisten();
  }

  if (tradeUnlisten) {
    tradeUnlisten();
  }

  if (contractTradeUnlisten) {
    contractTradeUnlisten();
  }

  if (globalTradeUnlisten) {
    globalTradeUnlisten();
  }

  if (marketDataUnlisten) {
    marketDataUnlisten();
  }

  if (configRequestUnlisten) {
    configRequestUnlisten();
  }

  if (accountCancelUnlisten) {
    accountCancelUnlisten();
  }

  if (globalRestoreCenterUnlisten) {
    globalRestoreCenterUnlisten();
  }

  // 异步清理行情订阅（不等待完成，避免阻塞组件卸载）
  cleanupCurrentSubscription().catch((error) => {});
});

// 将窗口信息获取函数暴露到全局，方便调试
if (typeof window !== "undefined") {
  (window as any).getCurrentWindowInfo = getCurrentWindowInfo;
}
</script>

<style scoped>
.trading-panel-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  background: #f0f0f0;
  display: flex;
  flex-direction: column;
}

/* 自定义标题栏样式 */
.custom-title-bar {
  height: 32px;
  background: #2c2c2c;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  border-bottom: 1px solid #404040;
  user-select: none;
  flex-shrink: 0;
}

.title-content {
  display: flex;
  align-items: center;
  font-size: 13px;
  font-weight: 500;
}

.contract-code {
  color: #ffffff;
}

.title-controls {
  display: flex;
  align-items: center;
}

.close-button {
  width: 32px;
  height: 24px;
  border: none;
  background: transparent;
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.close-button:hover {
  background: #e81123;
  color: #ffffff;
}

.close-button:active {
  background: #c50e1f;
}

/* 主交易面板样式 */
.trading-panel {
  display: flex;
  background: #c0c0c0;
  border: 1px solid #808080;
  font-family: "MS Sans Serif", sans-serif;
  font-size: 11px;
  flex: 1;
  height: calc(100vh - 32px);
  width: 100%;
  box-sizing: border-box;
  margin-top: 0;
}
</style>
